package com.stars.easyms.demo.restservice.datasource;

import com.stars.easyms.base.util.ExecutorUtil;
import com.stars.easyms.datasource.batch.BatchCommit;
import com.stars.easyms.demo.dao.TestDAO;
import com.stars.easyms.rest.RestService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

/**
 * <p>className: EasyMsDatasourceDemo8Service</p>
 * <p>description: 批量提交</p>
 *
 * @author guoguifang
 * @date 2019/9/27 16:18
 * @since 1.3.2
 */
@Service
public class EasyMsDatasourceDemo8Service implements RestService<Void, Void> {

    @Autowired
    private BatchCommit batchCommit;

    @Override
    public Void execute(Void input) {
        final int threadCount = 10, loopCount = 10, commitCount = 3000;
        List<Callable<Boolean>> callableList = new ArrayList<>();
        for (int i = 0; i < threadCount; i++) {
            callableList.add(() -> {
                for (int k = 0; k < loopCount; k++) {
                    List<Map<String,Object>> list = new ArrayList<>();
                    for (int j = 0; j < commitCount; j++) {
                        Map<String, Object> map = new HashMap<>(2);
                        map.put("name", "default");
                        map.put("age", j);
                        list.add(map);
                    }
                    // 使用默认数据源，可知相应sqlId且该sqlId基本不会变动的情况下使用该方法
                    // 若可能变动时也可将sqlId写在常量类中或者在可配置的配置文件中
                    batchCommit.batchInsert("com.stars.easyms.demo.dao.TestDao.batchInsertOracleData", list);
                }
                // 多数据源方式批量提交
                for (int k = 0; k < loopCount; k++) {
                    List<Map<String,Object>> list = new ArrayList<>();
                    for (int j = 0; j < commitCount; j++) {
                        Map<String, Object> map = new HashMap<>(2);
                        map.put("name", "other1");
                        map.put("age", j);
                        list.add(map);
                    }
                    // 使用非默认数据源，在DAO类中有对应方法时可以使用该方法，否则使用batchInsert(sqlId, list)的方法
                    batchCommit.batchInsert("other1", TestDAO.class, "batchInsertMysqlData", list);
                }
                return true;
            });
        }

        long startTime = System.currentTimeMillis();
        try {
            ExecutorUtil.submitAndDone(callableList);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(("批量提交" + (threadCount * loopCount * commitCount) + "条数据用时：" + (System.currentTimeMillis() - startTime)));
        return null;
    }

}